package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class LearningChangeListener {

    private final ILearningLessonService iLearningLessonService;

    //监听用户下单并添加课程到用户课表中
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.pay.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void listenLearningPay(OrderBasicDTO orderBasicDTO) {
        if (orderBasicDTO == null || orderBasicDTO.getUserId() == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds())) {
            log.error("接受MQ消息数据有误，无法处理");
            return;
        }

        log.info("接受到用户{}的订单{}，需要添加课程{}到课表中", orderBasicDTO.getUserId(), orderBasicDTO.getOrderId(), orderBasicDTO.getCourseIds());

        iLearningLessonService.addCourseToLesson(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "learning.lesson.refund.queue", durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenLearningRefund(OrderBasicDTO orderBasicDTO) {
        if (orderBasicDTO == null || orderBasicDTO.getUserId() == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds())) {
            log.error("接受MQ消息数据有误，无法处理");
            return;
        }

        log.info("接受到用户{}的退款订单{}，需要从课表中删除课程{}", orderBasicDTO.getUserId(), orderBasicDTO.getOrderId(), orderBasicDTO.getCourseIds());

        iLearningLessonService.deleteByCourseId(orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds().get(0));
    }
}
